from flask import Flask

from config import Config
from logger_config import LoggerConfig


def create_app(config_class=Config):
    """Flask 应用工厂函数"""
    app = Flask(__name__)
    app.config.from_object(config_class)

    # 配置日志系统
    app.logger = LoggerConfig.setup_logger('app', 'app.log')
    app.logger.info('应用启动')

    # 注册蓝图
    from app.routes.api import api_bp
    from app.modules4.web_app import app as order_stats_app
    from app.modules5.batch_flag_api import create_batch_flag_routes
    from app.modules6.newVendinfo import vendinfo_bp
    from app.modules7.erp_allocate_create import allocate_bp
    from app.moudules8.purch_data_api import purch_data_bp


    app.register_blueprint(api_bp, url_prefix='/api')
    app.register_blueprint(vendinfo_bp, url_prefix='/api')
    app.register_blueprint(order_stats_app)
    app.register_blueprint(allocate_bp, url_prefix='/api')
    app.register_blueprint(purch_data_bp, url_prefix='/api')

    # 注册批量更新商品标签路由
    create_batch_flag_routes(app)

    # 初始化调度器
    from app.scheduler import get_scheduler
    scheduler = get_scheduler(app)
    app.scheduler = scheduler

    # 注册CLI命令
    from app.modules1.Auto import auto_main
    
    @app.cli.command('auto')
    def auto_command():
        """运行自动任务命令"""
        success = auto_main()
        if success:
            print("自动任务执行成功")
        else:
            print("自动任务执行失败")
            
    return app